package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取会议通知信息
func GetMeetingInfo(p map[string]interface{}) *models.Meeting {
	o := orm.NewOrm()
	meeting := &models.Meeting{}
	qs := o.QueryTable("meeting")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["created"]; ok {
		qs = qs.Filter("created", p["created"])
	}
	qs.One(meeting)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if meeting.Id > 0 {
			meeting.CreatedShow = meeting.Created.Format("2006-01-02 15:04:05")
		}
	}
	return meeting
}

// 添加会议通知
func AddMeeting(input url.Values) (int64, error) {
	o := orm.NewOrm()
	meeting := &models.Meeting{}
	user := &models.User{}
	if _, ok := input["user_id"]; ok {
		user.Id = utils.Atoi64(input["user_id"][0])
		o.Read(user)
	}
	meeting.User = user
	class := &models.Class{}
	if _, ok := input["class_id"]; ok {
		class.Id = utils.Atoi64(input["class_id"][0])
		o.Read(class)
	}
	meeting.Class = class
	if _, ok := input["content"]; ok {
		meeting.Content = input["content"][0]
	}
	return o.Insert(meeting)
}

// 修改会议通知信息
func EditMeeting(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Meeting").Filter("id", input["id"][0]).Update(p)
}

// 获取会议通知列表
func GetMeetingList(p map[string]interface{}) (int64, []*models.Meeting) {
	var meetingList []*models.Meeting
	o := orm.NewOrm()
	qs := o.QueryTable("meeting")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["userId"]; ok {
		qs = qs.Filter("user_id", p["userId"])
	}
	if _, ok := p["classId"]; ok {
		qs = qs.Filter("class_id", p["classId"])
	}
	if _, ok := p["schoolId"]; ok {
		qs = qs.Filter("Class__School__Id", p["schoolId"])
	}
	if _, ok := p["classIds"]; ok && len(p["classIds"].([]int64)) > 0 {
		qs = qs.Filter("class_id__in", p["classIds"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if _, isLimit := p["limit"]; isLimit {
		qs = qs.Limit(p["limit"])
	} else if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&meetingList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, meeting := range meetingList {
			meeting.CreatedShow = meeting.Created.Format("2006-01-02 15:04:05")
			meeting.CreatedDateShow = meeting.Created.Format("2006-01-02")
		}
	}
	if _, ok := p["api"]; ok && p["api"].(bool) {
		for _, meeting := range meetingList {
			meeting.ClassName = meeting.Class.Name
			meeting.CreatedDateShow = meeting.Created.Format("2006-1-2")
		}
	}
	return totalCount, meetingList
}
